//
//  ZJView.m
//  DrawingBoard
//
//  Created by ZJ on 2018/8/10.
//  Copyright © 2018年 iCatch Technology Inc. All rights reserved.
//

#import "ZJView.h"
#import "ZJBezierPath.h"

@interface ZJView ()

//@property (nonatomic, strong) UIBezierPath *path;
@property (nonatomic, strong) NSMutableArray *paths; // 管理路径的数组

@end

@implementation ZJView

- (NSMutableArray *)paths {
    if (_paths == nil) {
        _paths = [NSMutableArray new];
    }
    
    return _paths;
}

// 清屏
- (void)clear {
    [self.paths removeAllObjects];
    // 重绘
    [self setNeedsDisplay];
}

// 回退
- (void)back {
    [self.paths removeLastObject];
    
    [self setNeedsDisplay];
}

// 橡皮
- (void)eraser {
    self.lineColor = self.backgroundColor;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    
    // 画线
    
    // 遍历所有的路径
    for (ZJBezierPath *path in self.paths) {
        // 设置连接处的样式
        [path setLineJoinStyle:kCGLineJoinRound];
        
        // 设置头尾的样式
        [path setLineCapStyle:kCGLineCapRound];
        
        // 设置颜色
        [path.lineColor set];
        
        // 渲染
        [path stroke];
    }
}

// 手指在这个 view 上触摸的时候调用
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 获取触摸对象
    UITouch *t = touches.anyObject;
    
    // 获取手指的位置
    CGPoint p = [t locationInView:t.view];
    
    ZJBezierPath *path = [[ZJBezierPath alloc] init];
    
    // 设置线宽
    [path setLineWidth:_lineWidth];
    // 记录线的颜色
    [path setLineColor:self.lineColor];
    
    // 起点
    [path moveToPoint:p];
    
    // 把每一次新创建的路径 添加到数组当中
    [self.paths addObject:path];
}

// 手指在这个 view 上移动的时候调用
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 获取触摸对象
    UITouch *t = touches.anyObject;
    
    // 获取手指的位置
    CGPoint p = [t locationInView:t.view];
    
    // 连线的点
    [[self.paths lastObject] addLineToPoint:p];
    // 重绘
    [self setNeedsDisplay];
}

@end
